<template>
  <!-- 试题录入卡片 -->
  <el-card ref="questionCard" class="box-card container">
    <div slot="header" class="clearfix">
      <span>{{ isEdit ? "试题修改" : "试题录入" }}</span>
    </div>

    <!-- 试题录入表单区域 -->
    <el-form ref="questionForm" :model="questionData" :rules="rules" label-width="80px">
      <!-- 学科 -->
      <el-form-item label="学科" prop="subjectID">
        <el-select v-model="questionData.subjectID" placeholder="请选择所属学科">
          <el-option v-for="subject in subjectsList" :key="subject.value" :label="subject.label" :value="subject.value"></el-option>
        </el-select>
      </el-form-item>

      <!-- 目录 -->
      <el-form-item label="目录" prop="catalogID">
        <el-select v-model="questionData.catalogID" placeholder="请选择所属目录">
          <el-option v-for="directory in directorysList" :key="directory.value" :label="directory.label" :value="directory.value"></el-option>
        </el-select>
      </el-form-item>

      <!-- 企业 -->
      <el-form-item label="企业" prop="enterpriseID">
        <el-select v-model="questionData.enterpriseID" placeholder="请选择所属企业">
          <el-option v-for="company in companysList" :key="company.id" :label="company.company" :value="company.id"></el-option>
        </el-select>
      </el-form-item>

      <!-- 城市 -->
      <el-form-item class="citys-select" label="城市" prop="province">
        <!-- 市级 -->
        <el-col :span="3" style="marginRight: 5px;">
          <el-select v-model="questionData.province" placeholder="请选择市">
            <el-option v-for="province in provinces" :key="province" :label="province" :value="province"></el-option>
          </el-select>
        </el-col>

        <!-- 区级 -->
        <el-col :span="3">
          <el-select v-model="questionData.city" placeholder="请选择区">
            <el-option v-for="city in citys" :key="city" :label="city" :value="city"></el-option>
          </el-select>
        </el-col>
      </el-form-item>

      <!-- 方向 -->
      <el-form-item label="方向" prop="direction">
        <el-select v-model="questionData.direction" placeholder="请选择所属方向">
          <el-option v-for="direc in direction" :key="direc" :label="direc" :value="direc"></el-option>
        </el-select>
      </el-form-item>

      <!-- 题型 -->
      <el-form-item label="题型" prop="questionType">
        <el-radio-group v-model="questionData.questionType">
          <el-radio v-for="qt in questionType" :key="qt.value" :label="`${qt.value}`">{{ qt.label }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 难度 -->
      <el-form-item label="难度" prop="difficulty">
        <el-radio-group v-model="questionData.difficulty">
          <el-radio v-for="diff in difficulty" :key="diff.value" :label="`${diff.value}`">{{ diff.label }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 题干 -->
      <el-form-item class="editor-container" label="题干" prop="question" error="题干不能为空！" :show-message="isQuestionEmpty">
        <quill-editor ref="editor" v-model="questionData.question" class="myQuillEditor" :options="editorOption" @blur="onEditorBlur(true)" />
      </el-form-item>

      <!-- 选项 -->
      <el-form-item v-show="optionsPanel === 1 || optionsPanel === 2" label="选项" class="options">
        <el-row v-for="(option, index) in questionData.options" :key="index">
          <el-radio v-if="optionsPanel === 1" v-model="option.isRight" :label="true" @click.native.prevent="handleOptionClick(index)">{{ `${option.code}:` }}</el-radio>
          <el-checkbox v-else-if="optionsPanel === 2" v-model="option.isRight">{{ `${option.code}:` }}</el-checkbox>
          <el-input v-model="option.title" placeholder="请输入选项"></el-input>
          <el-upload class="avatar-uploader" action="" :show-file-list="false" :data="{ index }" :http-request="beforeAvatarUpload">
            <img v-if="option.img" :src="option.img" class="avatar" />
            <span v-else class="">上传图片</span>
            <i class="el-icon-circle-close" @click.stop="calcelImg(index)"></i>
          </el-upload>
        </el-row>
        <el-button :disabled="optionsPanel !== 2" type="danger" size="small" @click="addOption">+增加选项与答案</el-button>
      </el-form-item>

      <!-- 解析视频 -->
      <el-form-item label="解析视频" style="width: 300px;">
        <el-input v-model="questionData.videoURL"></el-input>
      </el-form-item>

      <!-- 答案解析 -->
      <el-form-item class="editor-container" label="答案解析" prop="answer" error="题目解析不能为空！" :show-message="isAnswerEmpty">
        <quill-editor ref="editor" v-model="questionData.answer" class="myQuillEditor" :options="editorOption" @blur="onEditorBlur(false)" />
      </el-form-item>

      <!-- 题目备注 -->
      <el-form-item label="题目备注">
        <el-input type="textarea" v-model="questionData.remarks" style="width: 300px;"></el-input>
      </el-form-item>

      <!-- 试题标签 -->
      <el-form-item label="试题标签" prop="tags">
        <el-select v-model="questionData.tags" multiple filterable allow-create default-first-option placeholder="请选择试题标签">
          <el-option v-for="tag in tags" :key="tag.id" :label="tag.tagName" :value="tag.tagName">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 提交，确认修改 -->
      <el-form-item>
        <el-button type="primary" @click.native.prevent="onSubmit">{{
          isEdit ? "确认修改" : "确认提交"
        }}</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
// 导入获取题目详情api
import { detail as getQuestionDetail, add, update } from '@/api/hmmm/questions'
// 导入获取学科列表api
import { simple as getSubjects } from '@/api/hmmm/subjects'
// 导入获取目录列表api
import { simple as getDirectorys } from '@/api/hmmm/directorys'
// 导入获取企业列表api
import { list as getCompanys } from '@/api/hmmm/companys'
// 导入获取城市列表api
import { provinces, citys } from '@/api/hmmm/citys'
// 导入常量信息
import { difficulty, questionType, direction } from '@/api/hmmm//constants'
// 获取标签信息
import { list as getTags } from '@/api/hmmm/tags'
// 导入富文本编辑器及其样式
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { editorOption } from '@/utils/quillEditor.js'

export default {
  name: 'QuestionsNew',
  components: {
    quillEditor
  },
  data () {
    return {
      isEdit: this.$route.query.id ? Number(this.$route.query.id) : false,
      questionData: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: this.singleOptions,
        videoURL: '',
        answer: '',
        remarks: '',
        tags: []
      },
      rules: {
        subjectID: [
          {
            required: true,
            message: '请选择学科!',
            trigger: ['blur', 'change']
          }
        ],
        catalogID: [
          {
            required: true,
            message: '请选择目录!',
            trigger: ['blur', 'change']
          }
        ],
        enterpriseID: [
          {
            required: true,
            message: '请选择企业!',
            trigger: ['blur', 'change']
          }
        ],
        province: [
          {
            required: true,
            message: '请选择城市!',
            trigger: ['blur', 'change']
          }
        ],
        city: [
          {
            required: true,
            message: '请选择区域!',
            trigger: ['blur', 'change']
          }
        ],
        direction: [
          {
            required: true,
            message: '请选择方向!',
            trigger: ['blur', 'change']
          }
        ],
        questionType: [
          {
            required: true,
            message: '请选择题目类型!',
            trigger: ['blur', 'change']
          }
        ],
        difficulty: [
          {
            required: true,
            message: '请选择题目难度!',
            trigger: ['blur', 'change']
          }
        ],
        question: [
          {
            required: true,
            message: '请填写问题描述!',
            trigger: ['blur', 'change']
          }
        ],
        answer: [
          {
            required: true,
            message: '请填写题目解答!',
            trigger: ['blur', 'change']
          }
        ],
        tags: [
          {
            required: true,
            message: '请选择标签!',
            trigger: 'blur'
          }
        ]
      },
      subjectsList: [],
      directorysList: [],
      companysList: [],
      citys: [],
      tags: [],
      optionsPanel: 1,
      singleOptions: [
        {
          code: 'A',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: false
        }
      ],
      mutipleOptions: [
        {
          code: 'A',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: false
        }
      ],
      tagsString: '',
      isQuestionEmpty: false,
      isAnswerEmpty: false
    }
  },
  mounted () {
    // 获取学科信息
    this.getSubjectsList()
    // 获取企业信息
    this.getCompanysList()
    if (this.isEdit) {
      // 编辑-数据回显
      this.getQuestion()
    } else {
      // 初始化添加试题选项
      this.questionData.options = this.singleOptions
    }
  },
  watch: {
    'questionData.subjectID' (newSubjectID) {
      // console.log('获取目录')
      this.getDirectorysList(newSubjectID)
      this.getTagsList(newSubjectID)
    },
    'questionData.province' (newProvince) {
      this.citys = citys(newProvince)
    },
    'questionData.questionType' (newQuestionType) {
      if (newQuestionType === '1') {
        // 修改展示选项状态位
        this.optionsPanel = 1
        // 选项内容修改为单选
        this.questionData.options = this.singleOptions
      } else if (newQuestionType === '2') {
        // 修改展示选项状态位
        this.optionsPanel = 2
        // 选项内容修改为多选
        this.questionData.options = this.mutipleOptions
      } else if (newQuestionType === '3') {
        // 修改展示选项状态位
        this.optionsPanel = 3
      }
    },
    'questionData.tags' (newTags) {
      // console.log('修改', newTags)
      this.tagsString = Array.prototype.join.call(newTags, ',')
    }
  },
  computed: {
    provinces () {
      return provinces()
    },
    direction () {
      return direction
    },
    questionType () {
      return questionType
    },
    difficulty () {
      return difficulty
    },
    editorOption () {
      return editorOption
    },
    optionCode () {
      return ['A', 'B', 'C', 'D', 'E', 'F', 'G']
    }
  },
  methods: {
    // 取消图片上传文件
    calcelImg (index) {
      this.questionData.options[index].img = ''
    },

    // 点击上传图片
    beforeAvatarUpload ({ data, file }) {
      const index = data.index
      this.questionData.options[index].img = URL.createObjectURL(file)
    },

    // 获取题目详情-(修改试题信息功能)
    async getQuestion () {
      const { data } = await getQuestionDetail({ id: this.isEdit })
      // console.log(data)
      // 处理回显数据格式
      data.tags = data.tags.split(',')
      // 数据回显
      this.questionData = data
      // 存储选择类型题目的选项数据
      if (data.questionType === '1') {
        this.singleOptions = data.options
      } else if (data.questionType === '2') {
        this.mutipleOptions = data.options
      }
      // 修正页面滚动和富文本编辑器自动对焦问题
      this.$nextTick(() => {
        // 失去焦点
        this.$refs.editor.quill.blur()
        // 回滚到顶部
        document.documentElement.scrollTop = 0
      })
      // 获取回显provinces对应citys列表
      this.citys = citys(this.questionData.province)
    },

    // 获取学科列表
    async getSubjectsList () {
      const { data, status } = await getSubjects({ pagesize: 100 })
      // console.log(data)
      if (status === 200) {
        this.subjectsList = data
      } else {
        this.$message.error('学科列表获取失败!')
      }
    },

    // 获取目录列表
    async getDirectorysList (subjectID = '') {
      const { data } = await getDirectorys({
        pagesize: 100,
        subjectID: subjectID
      })
      // console.log(data)
      this.directorysList = data
    },

    // 获取企业列表
    async getCompanysList () {
      const { data } = await getCompanys({ pagesize: 100 })
      // console.log(data)
      this.companysList = data.items
    },

    //  获取标签
    async getTagsList (subjectID) {
      const { data } = await getTags({ pagesize: 100, subjectID: subjectID })
      // console.log(data)
      this.tags = data.items
    },

    // 处理选项点击事件
    handleOptionClick (rightIndex) {
      const qType = this.questionData.questionType
      const options = this.questionData.options
      // 判断当前是单选还是多选
      if (qType === '1' && !options[rightIndex].isRight) {
        // 单选,并且当前点击选项未被选中
        options.forEach((item, index) => {
          item.isRight = false
          if (index === rightIndex) {
            item.isRight = true
          }
        })
      } else if (qType === '2') {
        // 多选,
        options[rightIndex].isRight = true
      }
    },

    // 多选添加选项
    addOption () {
      const index = this.questionData.options.length
      if (index <= 6) {
        this.questionData.options.push({
          code: this.optionCode[index],
          title: '',
          img: '',
          isRight: 0
        })
      } else {
        this.$message.warning('最多只能添加7个选项')
      }
    },

    // 富文本编辑器非空验证
    onEditorBlur (isQuestionE) {
      if (isQuestionE) {
        const content = this.questionData.question.trim()
        if (content !== '') {
          this.isQuestionEmpty = false
        } else {
          this.isQuestionEmpty = true
        }
      } else {
        const content = this.questionData.answer.trim()
        if (content !== '') {
          this.isAnswerEmpty = false
        } else {
          this.isAnswerEmpty = true
        }
      }
    },

    // 确认提交，确认修改
    onSubmit () {
      // 表单兜底验证
      this.$refs.questionForm.validate(async isPass => {
        if (isPass && !this.isQuestionEmpty && !this.isAnswerEmpty) {
          // 替换部分表表单数据
          this.questionData.tags = this.tagsString
          // 判断当前是添加还是编辑
          if (this.isEdit) {
            const res = await update(this.questionData)
            if (res.status === 200) {
              this.$message.success(('题目更新成功，跳转基础题库中...'))
              // 跳转基础题库页面
              this.$router.push({ path: '/questions/list' })
            }
          } else {
            const res = await add(this.questionData)
            if (res.status === 200) {
              this.$message.success(('题目添加成功，跳转基础题库中...'))
              // 跳转基础题库页面
              this.$router.push({ path: '/questions/list' })
            }
          }
        } else {
          this.$message.error('验证不通过，请核对后提交!')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.container {
  margin: 15px 20px;
}
.options {
  .el-radio {
    margin-right: 0;
  }
  .el-input {
    margin-left: 10px;
    width: 250px;
  }
  .el-row {
    margin: 10px 0;
  }
}
.el-select {
  width: 300px;
}
.citys-select {
  /deep/.el-select {
    width: 145px;
  }
}
.avatar-uploader {
  width: 80px;
  height: 50px;
  display: inline-block;
  text-align: center;
  line-height: 50px;
  border: 1px dashed #c7cacf;
  margin-left: 10px;
  border-radius: 8px;
  font-size: 12px;
  position: relative;
  :hover {
    border: rgb(81, 206, 255);
    color: rgb(81, 206, 255);
  }
  .el-icon-circle-close {
    position: absolute;
    top: -6px;
    right: -6px;
    font-size: 18px;
  }
}

.avatar {
  width: 100%;
  border-radius: 8px;
}

.editor-container {
  margin-bottom: 30px;
  height: 230px;
  /deep/.el-form-item__content {
    height: 230px !important;
  }
}

.quill-editor {
  height: 160px !important;
}
.myQuillEditor {
  height: 160px !important;
}

/deep/.el-upload {
  vertical-align: middle;
  height: 100%;
  overflow: hidden;
  border-radius: 8px;
}
</style>
